import { openDB } from 'idb'

export const INDEXEDDB_REVEZONE_COMMON_KEY = 'common'
export const INDEXEDDB_REVEZONE_COMMON = 'revezone_common'

class CommonIndexeddbStorage {
  constructor() {
    if (CommonIndexeddbStorage.instance) {
      return CommonIndexeddbStorage.instance
    }

    CommonIndexeddbStorage.instance = this(async () => {
      this.db = await this.initDB()
    })()
  }
  static instance

  db
  async initDB() {
    if (this.db) {
      return this.db
    }

    const db = await openDB(INDEXEDDB_REVEZONE_COMMON, 1, {
      upgrade: async (db) => {
        await this.initCommonStore(db)
      }
    })

    this.db = db

    return db
  }

  async initCommonStore(db) {
    const boardStore = await db.createObjectStore(INDEXEDDB_REVEZONE_COMMON_KEY, {
      autoIncrement: true
    })

    return boardStore
  }

  async updateCommonData(key, data) {
    await this.initDB()
    await this.db?.put(INDEXEDDB_REVEZONE_COMMON_KEY, data, key)
  }

  async getCommonData(key) {
    await this.initDB()
    return await this.db?.get(INDEXEDDB_REVEZONE_COMMON_KEY, key)
  }

  async deleteCommonData(key) {
    await this.initDB()

    await this.db?.delete(INDEXEDDB_REVEZONE_COMMON_KEY, key)
  }
}

export const commonIndexeddbStorage = new CommonIndexeddbStorage()
